package yzbx.personalwebsite.webSocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * {@code @Author} zxm
 * {@code @Description} ws配置聊天室实现类
 * {@code @Date} 2024/11/15/13:22
 * {@code @Version} 1.0
 */
@Component
public class WebSocketTalk extends TextWebSocketHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketTalk.class);

    // 客户端和服务端建立 websocket 连接之后执行
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        LOGGER.info("websocket 连接成功");
    }

    // 对方传来 websocket 数据帧的时候执行
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        LOGGER.info("websocket 接收到消息：{}", message.toString());
        //向对端发送消息
        //session.sendMessage(message);
        //获取HttpSession中的属性
        session.getAttributes().get("user");
    }

    // websocket 连接出现异常的时候执行
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        LOGGER.info("websocket 连接异常：{}", exception.toString());
    }

    // 关闭 websocket 连接后执行
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        LOGGER.info("websocket 断开连接");
        sessions.remove(session);
    }

    // 存储WebSocket会话的集合，便于向特定会话发送消息
    private static final Set<WebSocketSession> sessions = new HashSet<>();

    // 向所有连接的客户端发送消息
    public static void sendMessageToAll() {
        for (WebSocketSession session : sessions) {
            try {
                session.sendMessage(new TextMessage("有新消息"));
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
            }
        }
    }
}
